import uuid
from random import random, randint, choice

from flask import Blueprint, jsonify, session
from flask_restful import Api, Resource, reqparse, inputs, fields, marshal
from werkzeug.security import generate_password_hash, check_password_hash

from utils import send_sms
from ext import cache, db
from apps.models.user_model import UserNews

user_news_bp = Blueprint('user', __name__)
api = Api(user_news_bp)


# 发送手机验证码视图
sms_parser = reqparse.RequestParser()
sms_parser.add_argument('mobile', type=inputs.regex(r'^1[356789]\d{9}$'), help='请输入正确的手机号', required=True)
class SendMessageApi(Resource):
    def post(self):
        args = sms_parser.parse_args()
        mobile = args.get('mobile')
        ret, code = send_sms(mobile)
        print('--------->' + '接受到请求')
        print(mobile)
        if ret is not None:
            # cache.set(mobile, code, timeout=1800)
            return jsonify(code=200, msg='短信发送成功！')
        else:
            return jsonify(code=400, msg='短信发送失败')


# 输入
login_parser = sms_parser.copy()
login_parser.add_argument('code', type=inputs.regex(r'^\d{4}$'), help='请输入四位验证码', required=True)

# 输出
user_fields = {
    'id': fields.Integer,
    'name': fields.String(attribute = 'username')
}


# 用户登录和注册 2356
class LoginAndRegisterApi(Resource):
    def post(self):
        args = login_parser.parse_args()
        mobile = args.get('mobile')
        code = args.get('code')
        # cache_code = cache.get(mobile)
        cache_code = "2365"
        if cache_code and str(code) == str(cache_code):
            # 数据库中是否存在此mobile
            user = UserNews.query.filter(UserNews.phone == mobile).first()
            if not user:  # 注册
                user_new = UserNews()
                user_new.phone = mobile
                s = ''
                for i in range(13):
                    ran = randint(0, 9)
                    s += str(ran)
                user_new.username = '用户' + s
                db.session.add(user_new)
                db.session.commit()
                user = user_new
            # 登录 记录登录状态 session cookie cache(redis)
            token = str(uuid.uuid4()).replace('-', '') + str(randint(100, 199))
            # cache.set(token, mobile)
            return {'user': marshal(user, user_fields), 'token': token}
        else:
            return {'msg': '验证码错误', 'code': 400}


class GetMessage(Resource):
    def get(self):
        return {'msg': '获取成功！', 'code': 200}


# 发送手机验证码
api.add_resource(SendMessageApi, '/sms')
api.add_resource(LoginAndRegisterApi, '/codelogin')
api.add_resource(GetMessage, '/getmessage')